﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ClickToEditTextBlock.Controls
{
	public partial class ClickToEditTextBlock : UserControl
	{
		public ClickToEditTextBlock()
		{
			InitializeComponent();
			TextBlock.DataContext = this;
			TextBox.DataContext = this;

			this.MouseLeftButtonDown += ClickToEditTextBlock_MouseLeftButtonDown;
		}

		#region Dependency Properties

		public static readonly DependencyProperty TextProperty =
			DependencyProperty.Register("Text", typeof(string), typeof(ClickToEditTextBlock), null);

		public string Text
		{
			get { return GetValue(TextProperty).ToString(); }
			set { SetValue(TextProperty, value); }
		}

		public static readonly DependencyProperty IsEditingProperty =
			DependencyProperty.Register("IsEditing", typeof(bool), typeof(ClickToEditTextBlock), 
			new PropertyMetadata(false, IsEditingPropertyChanged));

		public bool IsEditing
		{
			get { return (bool)GetValue(IsEditingProperty); }
			set { SetValue(IsEditingProperty, value); }
		}

		public static void IsEditingPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
		{
			var s = sender as ClickToEditTextBlock;
			if (s != null && (bool)e.NewValue)
			{
				s.Dispatcher.BeginInvoke(() =>
											{
												s.TextBox.Focus();
												s.TextBox.SelectAll();
											});

		}
		}
		#endregion

		#region Event Handlers

		private void TextBox_LostFocus(object sender, RoutedEventArgs e)
		{
			IsEditing = false;
		}


		private void ClickToEditTextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			IsEditing = true;
		}
		#endregion
	}
}
